import os
import time
from threading import Thread

import celery
import ujson

from celery.schedules import crontab
from django.conf import settings

ws_clients = []

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zhipin.settings')

app = celery.Celery(
    main='zhipin',
    broker='redis://:1Qaz2Wsx@47.104.31.138:54321/1',
    backend='redis://:1Qaz2Wsx@47.104.31.138:54321/2'
)

app.autodiscover_tasks(settings.INSTALLED_APPS)

# 配置定时任务（计划任务）
app.conf.update(
    timezone=settings.TIME_ZONE,
    enable_utc=True,
    # 定时任务（计划任务）相当于是消息的生产者
    # celery -A zhipin beat -l debug
    # celery -A zhipin worker -l debug
    beat_schedule={
        'task1': {
            'task': 'common.utils.display_info',
            'schedule': crontab('*', '*', '*', '*', '*'),
            'args': ('新浪微博是个垃圾！！！', )
        },
    },
)


def run_in_background():
    while True:
        for ws_client in ws_clients:
            ws_client.send(ujson.dumps({
                'message': 'hello'
            }))
        time.sleep(5)


Thread(target=run_in_background, daemon=True).start()
